package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.*;
import com.example.mapper.PictureMapper;
import com.example.mapper.RepairMapper;
import com.example.mapper.StateMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账单表业务处理
 **/
@Service
public class AdminRepairService {

    @Resource
    private RepairMapper repairMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private StateMapper stateMapper;

    /**
     * 新增
     */
    @Transactional
    public void add(Repair repair) {
        repair.setReportTime(DateUtil.now());
        // TODO 报修单号
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        repair.setRepairNumber("RO"+now.format(formatter));
//        Account currentUser = TokenUtils.getCurrentUser();
//        if (RoleEnum.USER.name().equals(currentUser.getRole())) {  // 只有用户才记录用户ID
//            bill.setUserId(currentUser.getId());
//        }

        repairMapper.insert(repair);

        List<String> pictures = repair.getPictures();
        for(String temp : pictures){
            Picture picture = new Picture();
            picture.setRepairNumber(repair.getRepairNumber());
            picture.setCover(temp);
            picture.setType("USER");
            pictureMapper.insert(picture);
        }

    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        repairMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            repairMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Repair repair) {
        repairMapper.updateById(repair);

        List<String> pictures = repair.getPictures();
        if(pictures!=null){
            for(String temp : pictures){
                Picture picture = new Picture();
                picture.setRepairNumber(repair.getRepairNumber());
                picture.setCover(temp);
                picture.setType("WORKER");
                pictureMapper.insert(picture);
            }
        }
    }

    /**
     * 根据ID查询
     */
    public Repair selectById(Integer id) {
        return repairMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Repair> selectAll(Repair repair) {
        return repairMapper.selectAll(repair);
    }

    /**
     * 分页查询
     */
    public PageInfo<Repair> selectPage(Repair repair, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Repair> list = repairMapper.selectAll(repair);
        List<Repair> resList = new ArrayList<>();
        for (Repair repair1 : list) {
            Picture picture = new Picture();
            picture.setRepairNumber(repair1.getRepairNumber());
            picture.setType("USER");
            List<Picture> pictures = pictureMapper.selectAll(picture);
            List<String> reportImages = pictures.stream().map(Picture::getCover)
                    .collect(Collectors.toList());
            repair1.setReportImages(reportImages);
            picture.setType("WORKER");
            List<Picture> picturesW = pictureMapper.selectAll(picture);
            List<String> repairImages = picturesW.stream().map(Picture::getCover)
                    .collect(Collectors.toList());
            repair1.setRepairImages(repairImages);
            resList.add(repair1);
        }
        return PageInfo.of(resList);
    }

    public List<Repair> count(String type) {
        Repair repair = new Repair();
        repair.setRepairType(type);
        List<Repair> repairList = repairMapper.selectAll(repair);  // 根据当前登录的用户ID查询到所有的账单信息
        List<String> categoryList = repairMapper.selectCategoryByType(type);
        List<Repair> list = new ArrayList<>();
//        for (String category : categoryList) {
//            Repair r = new Repair();
//            r.setCategory(category);
//            // 统计出当前这个分类的所有的金额汇总
//            BigDecimal categorySum = billList.stream().filter(bi -> bi.getCategory().equals(category)).map(Bill::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
//            // 返回当前分类的总金额
//            b.setMoney(categorySum);
//            // 得到账单的百分比
//            b.setPercent(categorySum.divide(sum, 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).intValue());
//            list.add(b);
//        }
        return list;
    }

    public double round2(double input) {
        // 使用BigDecimal来确保精确的舍入
        BigDecimal bd = BigDecimal.valueOf(input);
        // 设置小数点后保留两位，并使用HALF_UP模式进行四舍五入
        BigDecimal roundedBd = bd.setScale(2, RoundingMode.HALF_UP);
        // 将BigDecimal转换回double类型
        return roundedBd.doubleValue();
    }
    public StatsDto statuses(Repair repair) {
        List<Repair> list = repairMapper.selectAll(repair);
        StatsDto statsDto = new StatsDto();
        statsDto.setTotalRepairs(list.size());
        double success = 0;
        double rating = 0;
        for(Repair repair1 : list){
            if("已完成".equals(repair1.getRepairStatus())){
                success++;
            }
            if(repair1.getRating()!=null){
                rating += repair1.getRating();
            }
        }
        if(list.size()<1){
            statsDto.setSuccessRate(0d);
        }else{
            statsDto.setSuccessRate(round2(100*success/list.size()));
        }
        if(success<1){
            statsDto.setAverageRating(0d);
        }else{
            statsDto.setAverageRating(round2(rating/success));
        }
        return statsDto;
    }

    public List<RepairStatsDto> statusPie(Repair repair) {
        List<Repair> list = repairMapper.selectAll(repair);
        List<State> listState = stateMapper.selectAll(null);
        List<RepairStatsDto> listDto = new ArrayList<>();
        for(State state : listState){
            RepairStatsDto repairStatsDto = new RepairStatsDto();
            repairStatsDto.setName(state.getType());
            repairStatsDto.setValue((0));
            listDto.add(repairStatsDto);
        }
        for(Repair repair1 : list){
            if(repair1.getRepairStatus()!=null){
                String repairStatus = repair1.getRepairStatus();
                for(RepairStatsDto repairStatsDto : listDto){
                    if(repairStatus.equals(repairStatsDto.getName())){
                        repairStatsDto.setValue(repairStatsDto.getValue()+1);
                        break;
                    }
                }
            }
        }
        return listDto;
    }

    public List<Integer> ratingDistribution(Repair repair) {
        List<Repair> list = repairMapper.selectAll(repair);
        int[] arr = new int[5];
        for(Repair repair1 : list){
            if(repair1.getRating()!=null){
                arr[repair1.getRating()-1]++;
            }
        }
        return Arrays.stream(arr).boxed().collect(Collectors.toList());
    }

}